﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Xml;
using System.Windows.Input;
using SHomeWorkshop.LunarConcept.Widgets;
using SHomeWorkshop.LunarConcept.Controls;
using SHomeWorkshop.LunarConcept.Tools;
using SHomeWorkshop.LunarConcept.ModifingManager;

namespace SHomeWorkshop.LunarConcept
{
    /// <summary>
    /// 创建时间：2012年1月4日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：为主界面“常用图标”列表提供项目。
    /// </summary>
    public class ImageItem : System.Windows.Controls.TreeViewItem
    {
        public ImageItem(string imageDirectoryFullPath)
        {
            if (Directory.Exists(imageDirectoryFullPath) == false) return;

            //this.Focusable = false;//否则会导致上、下快捷键移动部件有时不起作用，用户可能莫名其妙。

            string[] imgFileFullPaths = System.IO.Directory.GetFiles(imageDirectoryFullPath);

            #region 树型框项目的头部。
            int index = imageDirectoryFullPath.LastIndexOf('\\');
            string shortname = null;
            if (index >= 0)
            {
                shortname = imageDirectoryFullPath.Substring(index + 1);
            }
            else
            {
                shortname = imageDirectoryFullPath;
            }

            this.Header = shortname;

            //this.ForeColor = Brushes.White;
            //this.BackColor = Brushes.Transparent;

            #endregion

            if (imgFileFullPaths.Length <= 0)
            {
                this.AddChild(new TreeViewItem().Header = "此类别无图像...");
            }
            else
            {
                //将所有项目都添加到树型框的内部。
                WrapPanel wpanel = new WrapPanel();
                wpanel.Width = 240;

                foreach (string filepath in imgFileFullPaths)
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.UriSource = new Uri(filepath, UriKind.Absolute);
                    bitmapImage.EndInit();

                    CImgButton imgButton = new CImgButton(filepath);
                    imgButton.MainImage.Source = bitmapImage;
                    imgButton.MainImage.Width = bitmapImage.PixelWidth;
                    imgButton.MainImage.Height = bitmapImage.PixelHeight;

                    imgButton.Click += new RoutedEventHandler(imgButton_Click);
                    wpanel.Children.Add(imgButton);
                }

                TreeViewItem tvi = new TreeViewItem();
                tvi.Header = wpanel;

                this.AddChild(tvi);
            }
        }

        void imgButton_Click(object sender, RoutedEventArgs e)
        {
            CImgButton button = sender as CImgButton;

            if (button == null) return;

            System.IO.FileInfo fileInfo = new FileInfo(button.ImgFileFullPath);

            if (fileInfo.Exists == false)
            {
                System.Windows.MessageBox.Show("　　文件不存在！在本程序已开始执行之后，您可能意外删除了如下位置的文件：\r\n" +
                    button.ImgFileFullPath, Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (Globals.MainWindow == null || Globals.MainWindow.EditorManager == null)
            {
                System.Windows.MessageBox.Show("　　整个文档中现在一个页面都没有，无处添加新图片框！",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            PageEditor mainPageEditor = Globals.MainWindow.EditorManager.GetMainSelectedPageEditor();

            if (mainPageEditor == null)
            {
                System.Windows.MessageBox.Show("　　请先点击某页面的目标位置，以便添加新图片框！",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            List<Widget> selectedWidgetList = Globals.MainWindow.EditorManager.GetSelectedWidgetsList();

            if (selectedWidgetList.Count <= 0)
            {
                InsertNewPictureBoxToPageEditor(button, mainPageEditor);
            }
            else
            {
                int selectedPictureBoxCount = 0;
                foreach (Widgets.Widget w in selectedWidgetList)
                {
                    if (w is Widgets.PictureBox) selectedPictureBoxCount++;
                }

                if (selectedPictureBoxCount == 0)
                {
                    InsertNewPictureBoxToPageEditor(button, mainPageEditor);
                    //如果当前选定的部件中没有图片框，那么就是要添加。
                }

                ModifingInfo info = new ModifingInfo() { ModifingDescription = "更改图像数据" };
                Globals.MainWindow.EditorManager.GetSelectedPageEditorStatus(info);
                Globals.MainWindow.EditorManager.GetSelectedWidgetStatus_Old(info);
                Globals.MainWindow.EditorManager.GetSelectedWidgetStatus_New(info);

                ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

                int skipedInnerIcons = 0;
                foreach (Widget w in selectedWidgetList)
                {
                    PictureBox pbox = w as PictureBox;
                    if (pbox == null) continue;

                    if (pbox.IsInnerIcon)
                    {
                        skipedInnerIcons++;
                        continue;
                    }

                    string oldValue = pbox.XmlData.InnerText;

                    pbox.LoadImageFromFile(button.ImgFileFullPath);

                    Action actReplaceImage = new Action(mainPageEditor.Id, pbox.Id, pbox.GetType().Name,
                        "ImageBase64", oldValue, pbox.XmlData.InnerText);

                    mi.AddAction(actReplaceImage);
                }

                Globals.MainWindow.EditorManager.RegisterModifingItem(mi);
                Globals.MainWindow.MainScrollViewer.Focus();

                if (skipedInnerIcons > 0)
                {
                    MessageBox.Show(string.Format(
                        "选定的部件中包括【{0}】个不允许更换图片的内置图标。已忽略对这些内置图标的操作。",
                        skipedInnerIcons), Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        private static void InsertNewPictureBoxToPageEditor(CImgButton button, PageEditor mainPageEditor)
        {
            ModifingInfo info = new ModifingInfo() { ModifingDescription = "添加图片框" };
            Globals.MainWindow.EditorManager.GetSelectedPageEditorStatus(info);
            Globals.MainWindow.EditorManager.GetSelectedWidgetStatus_Old(info);

            ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

            //在当前插入点位置插入新图片框。
            XmlNode widgetSetNode = mainPageEditor.WidgetSetNode;
            XmlNode newNode = widgetSetNode.AppendXmlAsChild(Properties.Resources.PictureBoxXml);
            PictureBox pbox = new PictureBox(mainPageEditor);
            pbox.XmlData = newNode;
            pbox.NewID();
            pbox.Location = mainPageEditor.BaseInsertPoint;
            pbox.LoadImageFromFile(button.ImgFileFullPath);

            Action actAddPictureBox = new Action(ActionType.WidgetAdded, mainPageEditor.Id, pbox.Id, null,
                pbox.XmlData.OuterXml);

            mainPageEditor.AddWidget(pbox);

            mi.AddAction(actAddPictureBox);
            pbox.SelectOnlySelf();

            info.NewMainSelectedWidgetID = pbox.Id;

            Globals.MainWindow.EditorManager.RegisterModifingItem(mi);
            Globals.MainWindow.MainScrollViewer.Focus();
        }
    }

    public class CImgButton : Button
    {
        public string ImgFileFullPath { get; set; }

        public Image MainImage { get; set; }

        public CImgButton(string imgFileFullPath)
        {
            //Focusable = false;

            Background = Brushes.White;
            ImgFileFullPath = imgFileFullPath;
            MainImage = new Image();
            Content = MainImage;
            TextBlock tb = new TextBlock();

            int index = imgFileFullPath.LastIndexOf('\\');
            string shortname = "";
            if (index >= 0)
            {
                shortname = imgFileFullPath.Substring(index + 1);
            }

            if (shortname != null)
            {
                tb.Text = shortname + "\r\n═════════\r\n点击图片插入到文档";
            }
            else
            {
                tb.Text = "点击图片插入到文档";
            }

            ToolTip = tb;
        }
    }
}
